﻿// IWebWF
// Copyright (c) 2008
// by Michael Washington
// Webmaster@ADefWebserver.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IWebWFCore;
using System.Web.Security;

namespace IWebWF
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
        {
            // Try to authendicate
            IWebWFDataContext IWebWFDataContext = new IWebWFDataContext();

            // Get allowed Login Failures
            int intAllowedLoginFailures = Convert.ToInt32(IWebWFDataContext.IWebWFSettings.FirstOrDefault(x => x.Setting == "MaxLoginAttempts").SettingValue);

            var result = from WFUser in IWebWFDataContext.IWebWFUsers
                         where WFUser.UserName == LoginControl.UserName
                         where WFUser.SuperUser == true
                         select WFUser;

            IWebWFUser IWebWFUser = (IWebWFUser)result.FirstOrDefault();

            if (IWebWFUser != null)
            {
                if (IWebWFUser.Password == LoginControl.Password)
                {
                    if (!IWebWFUser.Active)
                    {
                        LoginControl.FailureText = "Your account is not active. You cannot login until an administrator resets your account.";

                        // Log the event
                        ApplicationLog.AddToLog(IWebWFUser.UserName, "Login attempt. Account Not Active");
                    }
                    else if (IWebWFUser.Active)
                    {
                        // Set any possible failed login attempts back to 0
                        IWebWFUser.LoginFailures = 0;
                        IWebWFDataContext.SubmitChanges();

                        // Log the user into the site
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                          IWebWFUser.UserName,
                          DateTime.Now,
                          DateTime.Now.AddDays(30),
                          false,
                          IWebWFUser.Role,
                          FormsAuthentication.FormsCookiePath);

                        // Log the event
                        ApplicationLog.AddToLog(IWebWFUser.UserName, "User Logged In");

                        // Encrypt the ticket.
                        string encTicket = FormsAuthentication.Encrypt(ticket);

                        // Create the cookie.
                        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                        // Redirect back to original URL.
                        Response.Redirect(FormsAuthentication.GetRedirectUrl(IWebWFUser.UserName, false));
                    }
                }
                else
                {
                    // Bad Password
                    IWebWFUser.LoginFailures++;

                    // Is this user locked out?
                    if (IWebWFUser.LoginFailures >= intAllowedLoginFailures)
                    {
                        IWebWFUser.Active = false;
                        LoginControl.FailureText = "Your account has been locked out because of too many invalid login attempts. Please contact the administrator to have your account unlocked.";

                        // Log the event
                        ApplicationLog.AddToLog(IWebWFUser.UserName, "Account has been locked out because of too many invalid login attempts");
                    }
                    else
                    {
                        LoginControl.FailureText = String.Format("The password entered is incorrect. You have {0} more attempts", (intAllowedLoginFailures - IWebWFUser.LoginFailures).ToString());

                        // Log the event
                        ApplicationLog.AddToLog(IWebWFUser.UserName, String.Format("The password entered is incorrect. You have {0} more attempts", (intAllowedLoginFailures - IWebWFUser.LoginFailures).ToString()));
                    }

                    IWebWFDataContext.SubmitChanges();
                }
            }
            else
            {
                ApplicationLog.AddToLog(LoginControl.UserName, "Login attempt. Bad Username");
            }
        }
    }
}